#!/usr/bin/python3
# -*- coding: utf-8 -*-
import json
import traceback

from api import netbox_api, zabbix_api6

from loguru import logger
logger.add("/var/log/Task/Tasks.log", rotation="00:00", backtrace=True, diagnose=True, level="DEBUG")


# logger = logging.getLogger('netbox')

# -------同步组到zabbix-----------------
def zabbix_update_group(x, netbox_url, netbox_token, limit, verify, zabbix_server_url, zabbix_user, zabbix_passwd,
                        webhook_url):
    # global add_sites
    # global hosts_change_status
    # global sites_change_status
    # for x in firstDataList:

    try:
        # -----获取zabbix token-----------
        token = zabbix_api6.zabbix_get_token(zabbix_user, zabbix_passwd, zabbix_server_url, verify)

        # --------从netbox获取group信息-------------
        groupList = netbox_api.netbox_get_group(netbox_url, netbox_token, limit, verify)
        firstDataList = groupList[0:int(limit)]
        # os.system("echo '#' >  /root/netboxgroup")
        logger.info('初始化计数器')
        # logger.info("初始化计数器")
        add_sites = 0
        hosts_change_status = 0
        sites_change_status = 0

        # logger.info(x)
        # 将 name 对象解析为 name， 由接口返回结果知 name 是一个列表（数组）
        group_name = x['slug'] + '-' + x['name']
        # 搜索站点代码
        # group_info = zabbix_api6.zabbix_get_group(token, zabbix_server_url, 'name', x['slug'] + '-*', '0', verify)
        group_info = zabbix_api6.zabbix_get_group(token, zabbix_server_url, 'name', x['slug'] + '-*', False, verify)
        # 如果查询到组，则提示组已存在，并同步组状态否则创建组
        if group_info:
            logger.info(group_info[0]['name'] + '已存在,状态:' + str(x['status']['label']) + str(x['status']['value']))
            # logger.info(group_info[0]['name'] + '已存在,状态:' + str(x['status']['label']) + str(x['status']['value']))
            if x['status']['label'] == 'Active' and group_name == group_info[0]['name']:
                logger.info(group_info[0]['name'] + '状态已同步(' + str(x['status']['value']) + ')')
                resp_data = {"status": "None", "messqge": f"{group_info[0]['name']}状态已同步({str(x['status']['value'])})"}
                return resp_data
            # 如果netbox 状态是active，且zabbix非active，则启用zabbix组主机且更新组名
            elif x['status']['label'] == 'Active' and group_name != group_info[0]['name']:
                logger.info('启用组' + group_info[0]['name'] + '主机...')
                # logger.info('启用组' + group_info[0]['name'] + '主机...')
                logger.info('正在拉取' + group_info[0]['name'] + '主机列表..')
                # logger.info('正在拉取' + group_info[0]['name'] + '主机列表..')
                # 拉取组内host_列表
                hosts_list = zabbix_api6.zabbix_get2_hosts(token, zabbix_server_url, 'groupids', group_info[0]['groupid'],
                                                           verify)
                # 如果组内有主机，则启用主机（status 1-停用；status 0 启用）
                if hosts_list:
                    for host in hosts_list:
                        ret = zabbix_api6.zabbix_update_host(token, zabbix_server_url, host['hostid'], 'status', 0, verify)
                        logger.info('Host ' + host['name'] + '已启用')
                        # logger.info('Host ' + host['name'] + '已启用')
                        hosts_change_status = hosts_change_status + 1
                else:
                    logger.info('Hosts_list列表为空,Group ' + group_info[0]['name'] + '无host')
                    # logger.info('Hosts_list列表为空,Group ' + group_info[0]['name'] + '无host')
                # 更新组名，（状态标记）
                gret = zabbix_api6.zabbix_update_group(token, zabbix_server_url, group_info[0]['groupid'], 'name',
                                                       group_name, verify)
                logger.info('Group ' + group_info[0]['name'] + '已启用')
                logger.info('Group ' + group_info[0]['name'] + '已启用')
                sites_change_status = sites_change_status + 1
                resp_data = {"status": "Update", "message": f"Group{group_info[0]['name']}已启用"}
                return resp_data
                # return resp_data
            elif x['status']['label'] != 'Active' and group_name != group_info[0]['name']:
                logger.info(group_info[0]['name'] + '状态已同步(' + str(x['status']['value']) + ')')
                resp_data = {"status": "None", "message": f"{group_info[0]['name']}状态已同步({str(x['status']['value'])})"}
                return resp_data
            # 如果netbox 状态不是active，且zabbix是active，则停用zabbix组主机且更新组名
            elif x['status']['label'] != 'Active' and group_name == group_info[0]['name']:
                logger.info('停用组' + group_info[0]['name'] + '主机...')
                # logger.info('停用组' + group_info[0]['name'] + '主机...')
                logger.info('正在拉取' + group_info[0]['name'] + '主机列表..')
                # logger.info('正在拉取' + group_info[0]['name'] + '主机列表..')
                hosts_list = zabbix_api6.zabbix_get2_hosts(token, zabbix_server_url, 'groupids', group_info[0]['groupid'],
                                                           verify)
                # 如果组内有主机，则停用主机（status 1-停用；status 0 启用）
                if hosts_list:
                    for host in hosts_list:
                        ret = zabbix_api6.zabbix_update_host(token, zabbix_server_url, host['hostid'], 'status', 1, verify)
                        logger.info('Host ' + host['name'] + '已停用')
                        # logger.info('Host ' + host['name'] + '已停用')
                        hosts_change_status = hosts_change_status + 1
                else:
                    logger.info('Hosts_list列表为空,Group ' + group_info[0]['name'] + '无host')
                    # logger.info('Hosts_list列表为空,Group ' + group_info[0]['name'] + '无host')
                gret = zabbix_api6.zabbix_update_group(token, zabbix_server_url, group_info[0]['groupid'], 'name',
                                                       group_name + '-' + x['status']['label'], verify)
                logger.info('Group ' + group_info[0]['name'] + '已停用')
                logger.info('Group ' + group_info[0]['name'] + '已停用')
                sites_change_status = sites_change_status + 1
                resp_data = {"status": "Discard", "message": f"Group{group_info[0]['name']}已停用"}
                return resp_data
        else:
            if x['status']['label'] == 'Active':
                new_group = group_name
            else:
                new_group = group_name + '-' + x['status']['label']
            create_site_ret = zabbix_api6.zabbix_create_group(token, zabbix_server_url, new_group, verify)
            print('新增site:' + group_name + str(create_site_ret))
            logger.info('新增site:' + group_name + str(create_site_ret))
            add_sites = add_sites + 1
            # usergroup权限同步
            new_group_id = create_site_ret["result"]["groupids"][0]
            # 查询'Network Admin'组权限
            net_admin = zabbix_api6.zabbix_get_usergroup(token, zabbix_server_url, 'name', 'Network-Admin', '0', verify)
            print(f"net_admin{net_admin}")
            logger.info(f"net_admin{net_admin}")
            rights = net_admin[0].get('rights')
            rights.append({'permission': '3', 'id': new_group_id})  # 读写权限
            update_network_admin = zabbix_api6.zabbix_update_usergroup(token, zabbix_server_url, net_admin[0]["usrgrpid"], rights, verify)
            print("更新Network Admin 权限：" + json.dumps(update_network_admin))
            logger.info("更新Network Admin 权限：" + json.dumps(update_network_admin))
            # 更新'Network Read'权限
            rights = []
            net_read = zabbix_api6.zabbix_get_usergroup(token, zabbix_server_url, 'name', 'Network-Read', '0', verify)
            print(net_read)
            logger.info(net_read)
            rights = net_read[0].get('rights')
            rights.append({'permission': '2', 'id': new_group_id})  # 只读权限
            update_network_read = zabbix_api6.zabbix_update_usergroup(token, zabbix_server_url, net_read[0]["usrgrpid"], rights, verify)
            print("更新Network Read 权限：" + json.dumps(update_network_read))
            logger.info("更新Network Read 权限：" + json.dumps(update_network_read))
            # resp_data = {"message": f"更新Network Read 权限：{json.dumps(update_network_read)}"}
            # 更新'API-Read'权限-只读
            api_read = zabbix_api6.zabbix_get_usergroup(token, zabbix_server_url, 'name', 'API-Readd', '0', verify)
            print(api_read)
            logger.info(api_read)
            rights = api_read[0].get('rights')
            rights.append({'permission': '2', 'id': new_group_id})  # 只读权限
            update_api_read = zabbix_api6.zabbix_update_usergroup(token, zabbix_server_url, api_read[0]["usrgrpid"], rights, verify)
            print("更新API-Read 权限：" + json.dumps(update_api_read))
            logger.info("更新API-Read 权限：" + json.dumps(update_api_read))
            resp_data = {"status": "None", "message": f"更新API-Read 权限：{json.dumps(update_api_read)}, "
                                                      f"更新Network Admin 权限：{json.dumps(update_network_admin)}"
                                                      f"更新Network Read 权限：{json.dumps(update_network_read)}"}
            return resp_data
    except Exception as e:
        resp_data = {
            "hostname": x["name"],
            "status": "Error",
            "message": "同步site失败",
            "detail": traceback.format_exc()
        }
        logger.exception(traceback.format_exc())
        return resp_data
